package com.example.antivity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;

import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.Model.Essay;
import com.example.Model.EssayComment;
import com.example.Model.EssayRelated;
import com.example.UI.Mylistview;
import com.example.adapter.EssayComAdapter;
import com.example.adapter.EssayLvAdapter;

import com.example.retrofitinterface.EssayCommentInter;
import com.example.retrofitinterface.EssayInter;
import com.example.retrofitinterface.EssayRelatedInter;
import com.example.utils.GlideCircleTransform;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import org.xutils.DbManager;
import org.xutils.db.table.TableEntity;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import sdstcom.lbq.one.R;
import sdstcom.lbq.one.lbq.Databeans.DbBean;
import sdstcom.lbq.one.lbq.LBQapplication;

public class EssayActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    private EssayRelated essayrelated;
    private Toolbar tb;
    private TextView contenttv;
    private TextView titletv;
    private TextView authortv;
    private StringBuffer author;
    private TextView editor;
    private TextView editoremail;
    private ImageView authoriv;
    private TextView realthortv;
    private TextView authordesc;
    private ImageView relatediv;
    private Mylistview relatedlv;
    private TextView relatedtv;
    private EssayLvAdapter lvadapter;
    private WebView contentweb;
    private Mylistview commentlv;
    private ArrayList<EssayComment.DataBeanX.DataBean> list2;
    private ArrayList<EssayRelated.DataBean> relatedlist;
    private EssayComAdapter commentadapter;
    //
    private String title;
    private DbManager dbManager;
    private boolean ifpress = false;

    //private String url1 = "http://v3.wufazhuce.com:8000/api/essay/1690?platform=android&version=4.0.2&source=summary&uuid=ffffffff-acdc-5a02-0a04-a6b66eed847f&channel=91&source_id=9211";
    private String url;
    private String url1 = "http://v3.wufazhuce.com:8000/api/essay/";
    private String url2;
    private String url3 = "?platform=android&version=4.0.2&source=summary&uuid=ffffffff-acdc-5a02-0a04-a6b66eed847f&channel=91&source_id=";
    private String relatedurl1 = "http://v3.wufazhuce.com:8000/api/related/essay/";
    private String relatedurl3 = "?platform=android&version=4.0.2&uuid=ffffffff-acdc-5a02-0a04-a6b66eed847f&channel=9211";
    private String relatedurl;
    private String commenturl1 = "http://v3.wufazhuce.com:8000/api/comment/praiseandtime/essay/";
    private String commenturl3 = "/0?platform=android&version=4.0.2&uuid=ffffffff-acdc-5a02-0a04-a6b66eed847f&channel=91";
    private String commenturl;
    private Essay essay1;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_essay);
        dbManager=x.getDb(((LBQapplication)getApplication()).config);
        tb = (Toolbar) findViewById(R.id.tb);
        tb.setTitle("");
        setSupportActionBar(tb);
        tb.setNavigationIcon(R.mipmap.return_image_4_0);
        //返回监听
        tb.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        init();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void init() {
        url2 = getIntent().getStringExtra("itemid");
        url = url1 + url2 + url3;
        relatedurl = relatedurl1 + url2 + relatedurl3;
//        relatedurl = "http://v3.wufazhuce.com:8000/api/related/essay/"+url2+"l?platform=android&version=4.0.2&uuid=ffffffff-acdc-5a02-0a04-a6b66eed847f&channel=9211";
//        commenturl= "http://v3.wufazhuce.com:8000/api/comment/praiseandtime/essay/1710/0?platform=android&version=4.0.2&uuid=ffffffff-acdc-5a02-0a04-a6b66eed847f&channel=91";
        commenturl = commenturl1 + url2 + commenturl3;
        contenttv = (TextView) findViewById(R.id.essay_content);
        titletv = (TextView) findViewById(R.id.essay_title_tv);
        authortv = (TextView) findViewById(R.id.essay_author_tv);
        author = new StringBuffer();
        editor = (TextView) findViewById(R.id.essay_edit_tv);
        editoremail = (TextView) findViewById(R.id.essay_edi_emial_tv);
        authoriv = (ImageView) findViewById(R.id.essay_author_iv);
        realthortv = (TextView) findViewById(R.id.essay_author);
        authordesc = (TextView) findViewById(R.id.essay_author_desc);
        relatedlv = (Mylistview) findViewById(R.id.essay_related_lv);
        relatedlist = new ArrayList<>();
        lvadapter = new EssayLvAdapter(relatedlist, this);
        //相关推荐listview
        relatedlv.setAdapter(lvadapter);
        relatedlv.setOnItemClickListener(this);

        relatediv = (ImageView) findViewById(R.id.related_iv);
        relatedtv = (TextView) findViewById(R.id.related_tv);
       contentweb = (WebView) findViewById(R.id.essay_wv2);
        initwv();
        //评论listview
        commentlv = (Mylistview) findViewById(R.id.essay_comment_lv);
        list2 = new ArrayList<>();
        commentadapter = new EssayComAdapter(list2, this);
        commentlv.setAdapter(commentadapter);
        loadessay(url);
        loadrelated();
        loadcomment();


    }

    //文章及作者的下载
    private void loadessay(String url) {
        new Retrofit.Builder().baseUrl("http://v3.wufazhuce.com:8000/").
                addCallAdapterFactory(RxJavaCallAdapterFactory.create()).
                addConverterFactory(GsonConverterFactory.create()).
                build().create(EssayInter.class).getessay(url).subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Essay>() {
            @Override
            public void call(Essay essay) {
                essay1 = essay;

                //contenttv.setText(essay1.getData().getHp_content());
                //webview设置不使用缓存
                contentweb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
                //删除缓存数据

                //webview展示文章内容
                contentweb.loadData(essay1.getData().getHp_content(), "text/html; charset=UTF-8", null);
                contentweb.clearCache(true);
                contentweb.clearFormData();
                title = essay1.getData().getHp_title();
                titletv.setText(essay1.getData().getHp_title());
                for (int i = 0; i < essay1.getData().getAuthor().size(); i++) {
                    author.append(essay1.getData().getAuthor().get(i).getUser_name() + " ");
                }
                authortv.setText(author.toString());
                editor.setText(essay1.getData().getHp_author_introduce() + essay1.getData().getEditor_email());
                //图片圆角工厂
                GlideCircleTransform transform = new GlideCircleTransform(getApplication());
                if (essay1.getData().getAuthor().get(0).getWeb_url() != null) {
                    Glide.with(getApplication()).load(essay1.getData().getAuthor().get(0).getWeb_url()).transform(transform).into(authoriv);
                }
                realthortv.setText(essay1.getData().getAuthor().get(0).getUser_name());
                if (essay1.getData().getAuthor().get(0).getDesc() != null) {
                    authordesc.setText(essay1.getData().getAuthor().get(0).getDesc());
                }
            }
        });
    }

    //收藏按钮
    public void collection(View view) throws DbException {
        if (ifpress == false) {
            view.setPressed(true);
            DbBean dbBean = new DbBean();
            dbBean.setItemid(url2);
            dbBean.setType("essay");
            dbBean.setTitle(title);
            dbBean.setSubtype("essay");
            DbBean bean=dbManager.findById(DbBean.class,url2);
//            Log.e("TS", "collection: "+bean);
//            String sql="SELECT * FROM myonetable WHERE itemid="+url2;
            if (bean==null)
            {
                dbManager.save(dbBean);
                Toast.makeText(this,"收藏完成",Toast.LENGTH_SHORT).show();}
            ifpress=true;
        }else if (ifpress==true)
        {
            view.setPressed(false);
            dbManager.deleteById(DbBean.class,url2);
            ifpress=false;
            Toast.makeText(this,"取消收藏",Toast.LENGTH_SHORT).show();
        }

    }

    //喜欢按钮
    public void like(View view) {
        Button collection = (Button) view;
        collection.setPressed(true);
        Log.e("xxx", "点击了喜欢按钮");
    }

    //分享
    public void share(View view) {

    }
    private void initwv() {
//        Log.e("PATH",getIntent().getStringExtra("path"));

        //wv.loadUrl(getIntent().getStringExtra("path"));
        com.tencent.smtt.sdk.WebSettings settings=contentweb.getSettings();
        settings.setJavaScriptEnabled(true);

        // 设置加载进来的页面自适应手机屏幕
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);
        settings.setDisplayZoomControls(true);

        settings.setTextSize(com.tencent.smtt.sdk.WebSettings.TextSize.LARGEST);

        contentweb.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                webView.loadUrl(s);
                return true;
            }
        });
    }
    //相关推荐下载
    public void loadrelated() {
        new Retrofit.Builder().baseUrl("http://v3.wufazhuce.com:8000/").
                addCallAdapterFactory(RxJavaCallAdapterFactory.create()).
                addConverterFactory(GsonConverterFactory.create()).
                build().create(EssayRelatedInter.class).getessayrelated(relatedurl).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Action1<EssayRelated>() {
                    @Override
                    public void call(EssayRelated essayRelated) {
                        if (essayRelated.getData() != null) {
                            essayrelated = essayRelated;
                            relatedtv.setVisibility(View.VISIBLE);
                            relatediv.setVisibility(View.VISIBLE);
                            relatedlist.addAll(essayRelated.getData());
                            lvadapter.notifyDataSetChanged();
                        }

                    }
                });

    }

    //评论下载
    public void loadcomment() {
        new Retrofit.Builder().baseUrl("http://v3.wufazhuce.com:8000/").
                addCallAdapterFactory(RxJavaCallAdapterFactory.create()).
                addConverterFactory(GsonConverterFactory.create()).
                build().create(EssayCommentInter.class).getcomment(commenturl).
                subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Action1<EssayComment>() {
                    @Override
                    public void call(EssayComment essayComment) {
                        list2.addAll(essayComment.getData().getData());
                        commentadapter.notifyDataSetChanged();
                    }
                });

    }

    //创建文件，存入数据
    public void saveData(String content) throws IOException {
        OutputStream out = this.openFileOutput("content.html", Context.MODE_PRIVATE);
        /* 参数一: 文件名。
         * 如果文件不存在，Android会自动创建它。创建的文件保存在/data/data/<package name>/files目录下
         * 参数二: 文件操作模式参数。代表该文件是私有数据，只能被应用本身访问。
         * */
        Writer writer = new OutputStreamWriter(out);
        try {

            writer.write(content);
            Log.e("xxx", "saveData: 创建成更");
        } finally {
            writer.close();
        }
    }

    public void loadData() throws FileNotFoundException, IOException {
        BufferedReader reader = null;
        StringBuilder data = new StringBuilder();
        try {
            InputStream in = this.openFileInput("content.html");

            reader = new BufferedReader(new InputStreamReader(in));
            String line = new String();
            while ((line = reader.readLine()) != null) {
                data.append(line);
            }
            Toast.makeText(getApplication(), data.toString(), Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {

        } finally {
            reader.close();
        }
    }


    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }


    @Override
    protected void onResume() {
        super.onResume();
        //清除缓存
        CookieSyncManager cookieSyncMngr =
                CookieSyncManager.createInstance(getApplication());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    private void initurl(String url) {
        this.url = url;
    }

    //推荐listview监听
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        startActivity(new Intent(this, EssayActivity.class).putExtra("itemid", essayrelated.getData().get(position).getContent_id()));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        contentweb.destroy();
    }


}
